<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2019/3/21
 * Time: 10:09
 * 发现
 */
namespace app\api\controller;
use think\Db;
class Timer extends Base
{
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
//        extract(input());
//        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
//        if($auth == false){
//            echo json_encode(['status'=>301,'msg'=>"Token失效！请重新登录！"]);
//            exit;
//        }
    }
//    public function schoolRight()
//    {
//        $ss = Db::table('up_grade_class')
//            ->where('gs_role',1)
//            ->where('gs_school_id','>',0)
//            ->where('gs_grade_id','>',0)
//            ->where('gs_class_id','>',0)
//            ->field('count(*) num,gs_school_id')
//            ->group('gs_school_id')
//            ->select();
//        foreach ($ss as $k=>$v){
//            Db::table('up_school')
//                ->where('school_id', $v['gs_school_id'])
//                ->setField('school_student_num',$v['num']);
//
//        }
//        dump($ss);
//    }
    public function dowload() {//echo 1;die;
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if(strpos($agent, 'iphone') || strpos($agent, 'ipad'))
        {
            echo "<script> location.href='https://itunes.apple.com/cn/app/id1461726813'; </script>";
//            echo 'ios 下载地址';
        }else{
            echo "<script> location.href='http://ydmm.csyuedu.com/dowload/heart.apk'; </script>";
//            echo 'Android 下载地址';
        }

    }
    /**
     * 每礼拜执行一次：周经验清零
     */
    public function weekExpZero()
    {
        set_time_limit(0);
        //清零之前算一算这个人的经验有没有排到过前三或者冠军
        $users = Db::name('u_user')
            ->where('user_type', 1)
            ->where('user_class', '>', 0)
            ->group('user_school,user_grade,user_class')
            ->having('num >= 10')
            ->field('user_id,user_school,user_grade,user_class,count(*) num')
            ->select();
        if($users){
            foreach ($users as $k=>$v){
                $three = Db::name('u_user')
                    ->where('user_school',$v['user_school'])
                    ->where('user_grade',$v['user_grade'])
                    ->where('user_class',$v['user_class'])
                    ->where('user_exp_week','>',0)
                    ->order('user_exp_week DESC,user_exp_lasttime ASC')
                    ->field('user_id')
                    ->limit(0,3)
                    ->column('user_id');
                if($three){
                    if(isset($three[0])){
                        $this->getHonorForEvery ($three[0],8,1);
                        $this->getHonorForEvery ($three[0],9,1);
                    }
                    if(isset($three[1])){
                        $this->getHonorForEvery ($three[1],8,1);
                    }
                    if(isset($three[2])){
                        $this->getHonorForEvery ($three[2],8,1);
                    }

                }
            }
        }
        Db::name('u_user')
            ->where('user_id', '>', 0)
            ->update(['user_exp_week' => 0]);
        return true;
    }
    
    /**
     * 每月执行一次：月经验清零
     */
    public function monthExpZero()
    {
        set_time_limit(0);
        Db::name('u_user')
            ->where('user_id', '>', 0)
            ->update(['user_exp_month' => 0]);
        return true;
    }
    
    /**
     * 每年执行一次：年经验清零
     */
    public function yearExpZero()
    {
        set_time_limit(0);
        Db::name('u_user')
            ->where('user_id', '>', 0)
            ->update(['user_exp_year' => 0]);
        return true;
    }
    
    /**
     * 每天执行一次   修改优惠券状态
     * @return bool
     */
    public function oneDayCoupon()
    {
        $time = date('Y-m-d H:i:s');
        //未过期、上架中的优惠券列表
        $coupon = Db::table('up_coupon')
            ->where('coupon_end', '<', $time)
            ->where('coupon_status', 1)
            ->where('coupon_online', 1)
            ->field('coupon_id')
            ->select();
        if($coupon) {
            Db::startTrans();
            try {
                foreach($coupon as $k => $v) {
                    //修改优惠券状态
                    Db::table('up_coupon')->where('coupon_id', $v['coupon_id'])->setField('coupon_status', 2);
                    //修改我的优惠券状态
                    Db::table('up_my_coupon')
                        ->where('mc_status', 1)
                        ->where('mc_type', 1)
                        ->where('mc_coupon_id', $v['coupon_id'])
                        ->setField('mc_status', 3);
                }
                Db::commit();
            } catch(\Exception $e) {
                Db::rollback();
            }
        }
        return true;
    }
    //修改研学活动是否已经结束
    public function activity(){
        $time = date('Y-m-d H:i:s');
        $res = Db::table('up_notice')
            ->where('n_activity_status',1)
            ->where('n_type',1)
            ->select();
        foreach ($res as $key=>$vo){
            if($vo['n_end_time'] <= $time){
                Db::table('up_notice')->where('n_id',$vo['n_id'])->setField('n_activity_status',2);
            }
            if($vo['n_apply_end_time'] <= $time){
                Db::table('up_notice')->where('n_id',$vo['n_id'])->setField('n_sign_status',2);
            }
        }
    }
    //修改研学活动报名是否已经结束
    public function sign(){
        $res = Db::table('up_notice')
            ->where('n_full_status',1)
            ->where('n_type',1)
            ->select();
        foreach ($res as $key=>$vo){
            if($vo['n_num']==$vo['n_num_already']){
                Db::table('up_notice')->where('n_id',$vo['n_id'])->setField('n_full_status',2);
            }
        }
    }
    
    /**
     * 定时消息推送
     */
    public function sendForTuis(){
        $time = date('Y-m-d H');
        $unsend = Db::table('up_message')
            ->field('m_id, m_title, m_range, m_user, m_type, m_article_id, m_goods_id')
            ->where('m_way', 2)
            ->where('m_status', 1)
            ->where('m_time', '=', $time)
            ->select();
        if($unsend){
            foreach($unsend as $k => $v){
                if($v['m_range'] == 1){
                    $user_ids = Db::table('up_u_user')
                        ->where('user_status', 1)
                        ->column('user_id');
                }elseif($v['m_range'] == 2){
                    $user_ids = Db::table('up_u_user')
                        ->where('user_status', 1)
                        ->where('user_school', 'IN', $v['m_user'])
                        ->column('user_id');
                }else{
                    $user_ids = explode(',', $v['m_user']);
                }
                
                //article_type 文章类型，如果是商品，则为空    send_id  推送的内容ID
                if($v['m_type'] == 1){
                    $article_type = '';
                    $send_id = $v['m_goods_id'];
                }else{
                    $article_type = Db::table('up_notice')->where('n_id', $v['m_article_id'])->value('n_type');
                    $send_id = $v['m_article_id'];
                }
                $list = [];//需要推送的用户数组
                foreach($user_ids as $ke => $va){
                    $val = (string)$va;
                    array_push($list, $val);
                }
				Db::table('up_message')->where('m_id', $v['m_id'])->setField('m_status', 2);
                try{
                    $this->Jpush(1, $list, $v['m_title'], ['send_type' => 2, 'type' => $v['m_type'], 'send_id' => $send_id, 'n_type' => $article_type]);
                }catch(\Exception $e){
                    
                }
            }
        }
    }
    
    /**
     * 待付款订单提醒推送
     */
    public function unpaySend(){
        $time = date('Y-m-d H:i:s', strtotime('-20 minutes'));//20分钟之前的订单
        $where = [
            'order_status' => 1,//未支付
            'order_del' => 1,//未删除
            'order_send' => 1,//未推送
        ];
        $unpay = Db::table('up_order')
            ->where($where)
            ->whereTime('order_time', '<', $time)
            ->field('order_id, order_userid, order_status')
            ->select();
        if($unpay){
            foreach($unpay as $k => $v){
                $user_id = (string)$v['order_userid'];
                $str = '喵喵阅读：您有一笔待付款订单即将关闭，请及时处理';
                try{
                    $this->Jpush(1, $user_id, $str, ['send_type' => 5, 'order_id' => $v['order_id'], 'order_status' => $v['order_status']]);
                }catch(\Exception $e){
                    
                }
                Db::table('up_order')->where('order_id', $v['order_id'])->setField('order_send', 2);
            }
        }
    }
    
    /**
     * 极光推送
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $extras 扩展字段接受数组
     * @return array
     */
    public function Jpush($type,$alias,$message,$extras)
    {
//        $alias = (string)$alias;
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        return $push->send();
    }

    /**
     * 获取微博分享的一些信息（专为前端微博分享）
     * @return string
     */
    public function getWeiboNeed()
    {
        header('Access-Control-Allow-Origin:*');
        $rg_id = $_REQUEST['rg_id'];
        $game = Db::table('up_reading_game g')
            ->join ('up_reading_book b','g.rg_rb_id = b.rb_id','LEFT')
            ->where('rg_id',$rg_id)
            ->field('rb_name,rb_image,rg_name')
            ->find();
        return json_encode(['status'=>0,'msg'=>$game]);
    }
    /**
     * 第三方登录的隐藏和显示
     * @return string
     */
    public function threeYesNo()
    {
        header('Access-Control-Allow-Origin:*');
        return json_encode(['status'=>200,'msg'=>2]);
    }
    public function testpush()
    {
        import('jpush.autoload', EXTEND_PATH);
        header('Access-Control-Allow-Origin:*');
        $id = $_REQUEST['id'];
        if($id == ''){
            die('input your id!');
        }
        $type = 1;
        $alias = "$id";
        $message = '我是>>'.$id;
        $extras = ['aa'=>2,'bb'=>2];
//        $alias = (string)$alias;
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        return $push->send();
    }
}